<template>
  <div>
    <searchForm
      :formData="formData"
      :search="search"
      @searchHandle="onSubmit"
      @searchReset="searchReset"></searchForm>
    <div class="table">
      <div class="table-header">
        <div class="table-title">教师列表</div>
        <div class="btnGroup">
          <el-button-group>
            <el-button type="text" class="btn" icon="el-icon-plus" @click="goAddTeacher()"
              >添加教师</el-button
            >
            <el-button type="text" class="btn" icon="el-icon-delete" @click="deleteAll()"
              >批量删除</el-button
            >
            <el-button type="text" class="btn" icon="el-icon-edit" @click="calculate()"
              >导入计算</el-button
            >
            <el-button type="text" class="btn" icon="el-icon-download" @click="handleExport()"
              >导出</el-button
            >
            <el-button type="text" class="btn" icon="el-icon-edit" @click="$refs.Import.click()"
              >导入</el-button
            >
            <el-button type="text" class="btn" icon="el-icon-edit" @click="tuixiu = true"
              >退休人员学时优惠</el-button
            >
            <el-button type="text" class="btn" icon="el-icon-edit" @click="shuangjiantiao = true"
              >双肩挑工作量</el-button
            >
          </el-button-group>
        </div>
      </div>
      <el-table
        :data="tableData"
        row-key="id"
        stripe
        border
        max-height="400"
        ref="myTable"
        style="width: 100%"
        @select="handleSelect"
        @select-all="handleSelectAll">
        <el-table-column type="selection" width="55" :reserve-selection="true"> </el-table-column>
        <el-table-column prop="id" label="工号" width="120"> </el-table-column>
        <el-table-column prop="name" fixed="left" label="姓名" width="120"> </el-table-column>
        <el-table-column prop="role" fixed="left" label="角色" width="120"> </el-table-column>
        <el-table-column prop="level" label="等级" width="120"> </el-table-column>
        <el-table-column prop="profession" label="职称" width="120"> </el-table-column>
        <el-table-column prop="workYear" label="工作年限" width="120"> </el-table-column>
        <el-table-column prop="managerPro" label="管理员职务" width="120"> </el-table-column>
        <el-table-column prop="managerYear" label="管理员年限" width="120"> </el-table-column>
        <el-table-column prop="classHour" label="课时" width="120"> </el-table-column>
        <el-table-column prop="sciHour" label="科研学时" width="120"> </el-table-column>
        <el-table-column prop="publicService" label="公共服务" width="120"> </el-table-column>
        <el-table-column prop="otherSalary" label="其他绩效" width="120"> </el-table-column>
        <el-table-column prop="isRetirement" label="是否临近退休" width="120"> </el-table-column>
        <el-table-column prop="isGood" label="是否评优" width="120"> </el-table-column>
        <el-table-column prop="isFit" label="是否合格" width="120"> </el-table-column>
        <el-table-column prop="esScore" label="评价分数" width="120"> </el-table-column>
        <el-table-column prop="effectiveTime" label="有效时长" width="120"> </el-table-column>
        <el-table-column prop="overHour" label="超出工作学时" width="120"> </el-table-column>
        <el-table-column prop="score" label="绩效分" width="120"> </el-table-column>
        <el-table-column prop="bonus" label="奖金" width="120"> </el-table-column>
        <el-table-column label="操作" fixed="right" width="150">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          :current-page.sync="page"
          :page-size="pageSize"
          :page-sizes="sizes"
          layout="prev, pager, next, jumper,sizes,total"
          :total="total"
          @current-change="changePage"
          @size-change="changeSize" />
      </div>
    </div>
    <el-dialog title="计算前置数据导入" :visible.sync="dialogVisible" :before-close="handleClose">
      <el-form ref="form" :model="calculateData" label-width="80px">
        <el-form-item label="下发总金额">
          <el-input
            v-model="calculateData.totalAmount"
            size="small"
            placeholder="请输入下发总金额"></el-input>
        </el-form-item>
        <el-form-item label="分值">
          <el-input
            v-model="calculateData.scorePrice"
            size="small"
            placeholder="请输入分值"></el-input>
        </el-form-item>
        <el-form-item label="其他绩效和公共服务">
          <el-input
            v-model="calculateData.others"
            size="small"
            placeholder="请输入其他绩效和公共服务"></el-input>
        </el-form-item>
        <el-form-item label="未达标人员发放比例：">
          <el-input
            v-model="calculateData.failureRate"
            size="small"
            placeholder="请输入未达标人员发放比例："></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="calculate()">取 消</el-button>
      </span>
    </el-dialog>
    <el-dialog title="退休人员学时优惠比例" :visible.sync="tuixiu">
      <el-form>
        <el-form-item label="优惠比例" label-width="120px">
          <el-input autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="tuixiu = false">取 消</el-button>
        <el-button type="primary" @click="tuixiu = false">取 消</el-button>
      </span>
    </el-dialog>
    <el-dialog title="双肩挑人员学时工作量" :visible.sync="shuangjiantiao">
      <el-form>
        <el-form-item label="学时工作量" label-width="120px">
          <el-input autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="shuangjiantiao = false">取 消</el-button>
        <el-button type="primary" @click="shuangjiantiao = false">取 消</el-button>
      </span>
    </el-dialog>
    <input type="file" ref="Import" @change="handleImport" style="display: none" />
  </div>
</template>

<script>
import { mapMutations } from "vuex";
import searchForm from "@/components/searchForm/index";
import Pagination from "@/components/Pagination/Pagination.vue";
import { showMessage } from "@/utils/common";
export default {
  components: {
    Pagination,
    searchForm,
  },
  data() {
    return {
      search: {
        user: "",
      },
      formData: [
        {
          label: "教师姓名",
          model: "user",
          type: "input",
          clearable: true,
        },
      ],
      sizes: [10, 20, 50, 100],
      tableData: [],
      calculateData: {
        totalAmount: "4168382.08",
        scorePrice: "100",
        others: "187172.903618312",
        failureRate: "0.5",
      },
      total: 20,
      page: 1,
      pageSize: 20,
      dialogVisible: false,
      // isAllSelect: false,
      //Import: false,
      tuixiu: false,
      shuangjiantiao: false,
    };
  },
  methods: {
    ...mapMutations("addTeacher", ["changeTitle", "getFormData"]),
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    async handleImport(event) {
      // 获取选中的文件列表（FileList 对象）
      const file = event.target.files[0];
      console.log(file);
      const formData = new FormData();
      formData.append("file", file);
      try {
        const res = await this.$api.importExcel(formData);
        showMessage(res, this);
      } catch (error) {
        console.error("上传失败:", error);
      } finally {
        event.target.value = "";
      }
    },
    async handleExport() {
      try {
        // 1. 发送请求获取文件流（假设接口地址为 /api/export）
        const response = await this.$api.exportExcel();

        // 2. 创建 Blob 对象并生成下载链接
        const blob = new Blob([response.data]);
        const downloadUrl = window.URL.createObjectURL(blob);

        // 3. 创建虚拟链接并触发点击下载
        const link = document.createElement("a");
        link.href = downloadUrl;

        // 从响应头或自定义获取文件名（需后端配合）
        const fileName = this.getFileNameFromHeaders(response.headers) || "example.xlsx";
        link.download = fileName;

        document.body.appendChild(link);
        link.click();

        // 4. 清理临时对象
        window.URL.revokeObjectURL(downloadUrl);
        document.body.removeChild(link);
      } catch (error) {
        console.error("导出失败:", error);
        alert("文件导出失败，请重试！");
      }
    },

    // 从响应头解析文件名（示例）
    getFileNameFromHeaders(headers) {
      // 后端需设置 Content-Disposition: attachment; filename="example.xlsx"
      const contentDisposition = headers["content-disposition"];
      if (contentDisposition) {
        const fileNameMatch = contentDisposition.match(/filename="?(.+)"?/);
        if (fileNameMatch && fileNameMatch[1]) {
          return decodeURIComponent(fileNameMatch[1]); // 处理中文文件名
        }
      }
      return null;
    },
    handleSelect(selection, row) {
      console.log(selection, row);
    },
    handleSelectAll(selection) {
      // if (!this.isAllSelect) {
      //   this.$refs.myTable.clearSelection();
      //   this.isAllSelect = true;
      //   const res = await this.$api.getTeacher({
      //     page: 1,
      //     pageSize: 300,
      //   });
      //   const arr = res.data.data.records;
      //   console.log(arr);
      //   this.$nextTick(() => {
      //     arr.forEach((item) => {
      //       this.$refs.myTable.toggleRowSelection(item, true);
      //     });
      //   });
      // } else {
      //   this.isAllSelect = false;
      //   this.$refs.myTable.clearSelection();
      // }
      // this.$nextTick(() => {
      //   console.log(selection);
      // });
    },
    onSubmit() {
      if (this.search.user === "") return;
      this.getTableData({
        page: this.page,
        pageSize: this.pageSize,
        name: this.search.user,
      });
    },
    handleEdit(index, row) {
      console.log(index, row);
      this.changeTitle("编辑");
      this.getFormData(row);
      this.$router.push("/addTeacher");
    },
    deleteAll() {
      this.$confirm("此操作将永久删除该教师信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await this.$api.deleteTeacher(this.$refs.myTable.selection);
          if (res.data.code === 1) this.getTableData({ page: this.page, pageSize: this.pageSize });
          showMessage(res, this);
        })
        .catch(() => {});
    },
    handleDelete(index, row) {
      this.$confirm("此操作将永久删除该教师信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          console.log(index, row);
          const res = await this.$api.deleteTeacher([row]);
          if (res.data.code === 1) this.getTableData({ page: this.page, pageSize: this.pageSize });
          showMessage(res, this);
        })
        .catch(() => {});
    },
    calculate() {
      this.dialogVisible = true;
    },
    async calculateResult() {
      // const queryParams = new URLSearchParams(this.calculateData);
      // const query = `?${queryParams.toString()}`;
      // console.log(query);
      // const res = await this.$api.calculate(query);
      const params = {
        ...this.calculateData,
        teachersData: this.$refs.myTable.selection,
      };
      console.log(params);
      const res = await this.$api.calculate(params);
      this.dialogVisible = false;
      this.getTableData({ page: this.page, pageSize: this.pageSize });
      showMessage(res, this);
    },
    SizeChange(val) {
      console.log("home---每页" + val + "条");
      this.pageSize = val;
      this.getTableData({ page: this.page, pageSize: this.pageSize });
    },
    CurrentChange(val) {
      this.page = val;
      this.getTableData({ page: this.page, pageSize: this.pageSize });
    },
    blur() {
      if (!this.formInline.user) {
        this.getTableData({ page: this.page, pageSize: this.pageSize });
      }
    },
    async getTotal() {
      const res = await this.$api.getTeacherTotal();
      console.log(res);
      this.total = res.data.data;
    },
    async getTableData(obj) {
      const res = await this.$api.getTeacher(obj);
      this.tableData = res.data.data.records;
    },
    goAddTeacher() {
      this.changeTitle("添加");
      this.$router.push("/addTeacher");
    },
  },
  mounted() {
    this.getTotal();
    this.getTableData({ page: this.page, pageSize: this.pageSize });
  },
};
</script>

<style lang="less" scoped>
.table {
  display: flex;
  flex-direction: column;
  margin: 5px 20px;
  border: 1px solid #ddd;

  .table-header {
    display: flex;
    align-items: center;
    padding: 0px 15px;
    border-bottom: 1px solid #ddd;

    .table-title {
      font-size: 14px;
      padding: 2px 0;
    }
    .btnGroup {
      .btn {
        margin-left: 5px;
        padding-right: 5px;
        color: #00f;

        &:hover {
          background-color: #409eff;
          color: #fff;
        }
      }
    }
  }
}

.pagination {
  display: flex;
  justify-content: center;
  padding: 5px 15px;
  padding-top: 15px;
}
::v-deep .el-table__cell {
  font-size: 12px;
  color: #000;
}
::v-deep th.el-table__cell {
  height: 58px;
  text-align: center;
  padding: 0;
}

/deep/.el-dialog {
  width: 45% !important;
  margin-top: 25vh !important;
}
/deep/ .el-dialog__header {
}
/deep/ .el-dialog__body {
  padding-top: 5px;
}
/deep/ .el-form-item__content {
  display: flex;
}
/deep/ .el-form-item__label {
  width: 160px !important;
  text-align: center;
}
</style>
